import axios from 'axios'
import store from '../store'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 5000,
  headers: {
    icode: 'CFE133F50CCAEC3B'
  }
})

service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    const { success, data, message } = res.data
    if (success) {
      return data
    }
    return Promise.reject(new Error(message))
  },
  (err) => {
    if (err.response?.data?.code === 401) {
      // token失效
      store.dispatch('user/logout')
    }
  }
)

export default service
